#include "TcpSocketImpl.h"
#include "Timer.h"
#include <iostream>

TcpSocketImpl::TcpSocketImpl()
{
    timer = new Timer();
    timer->setTimerCallback(TcpSocketImpl::reConnectTimer, (void *) this);
}

TcpSocketImpl::~TcpSocketImpl()
{
    delete timer;
}

void TcpSocketImpl::read(const char *buf, size_t size)
{
    std::string str(buf, size);
    std::cout << "read:" << str.c_str() << std::endl;
}

void TcpSocketImpl::onConnect(bool status)
{
    if (status)
    {
        timer->stop();
    }
    else
    {
        timer->start(1000, 2000);
    }
}

void TcpSocketImpl::disconnected()
{

    std::cout << "server disconnected, start reconnect timer" << std::endl;

    timer->start(1000, 2000);
}

void TcpSocketImpl::onClose()
{
}

void TcpSocketImpl::reConnectTimer(void *data)
{
    auto thisPointer = static_cast<TcpSocketImpl *>(data);
    std::cout << "reconnect to the host" << std::endl;
    if (!thisPointer->connectToHost())
    {
        std::cout << "connect error:" << thisPointer->getLastErrorMessage().c_str() << std::endl;
    }
}
